package java3;

import java.util.concurrent.*;

/**
 * @Author 不知名网友鑫
 * @Date 2022/5/5
 * JDK5.0创建多线程的新方法：使用线程池创建多线程
 **/
class NumberThread implements Runnable{

    @Override
    public void run() {
        for(int i = 0;i <= 100;i++){
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        }
    }
}

class NumberThread1 implements Runnable{

    @Override
    public void run() {
        for(int i = 0;i <= 100;i++){
            if(i % 2 != 0){
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        }
    }
}
class NumberThread2 implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        int sum=10;
        return sum;
    }
}
public class ExectorServiceTest {
    public static void main(String[] args) {
        //1. 创建指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);
        //2. 创建线程池的方法之二：
         ExecutorService executor = new ThreadPoolExecutor(10, 10,
                60L, TimeUnit.SECONDS,
                new ArrayBlockingQueue(10));
        //  设置线程池的属性
        //  System.out.println(service.getClass());
        //  service1.setCorePoolSize(15);
        //  service1.setKeepAliveTime();

        //2. 执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象。
        executor.execute(new NumberThread());//适合适用于Runnable，适合于提交不需要返回值的内容。

        service.execute(new NumberThread1());

        //submit适合使用于Callable。会返回一个Future对象。

        Future<Integer> submit = service.submit(new NumberThread2());
        try {
            System.out.println(submit.get());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }

        //3.关闭连接池
        service.shutdown();
        executor.shutdown();
    }
}
